package org.hepeng.workx.mybatis.spring;

import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.springframework.context.ApplicationContext;

import java.util.Objects;

/**
 * @author he peng
 */
public class SpringObjectFactory extends DefaultObjectFactory {

    private ApplicationContext applicationContext;

    public SpringObjectFactory(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public <T> T create(Class<T> type) {
        T t;
        try {
            t = super.create(type);
            if (Objects.isNull(t)) {
                t = getBeanFromSpringContext(type);
            }
        } catch (Exception e) {
            t = getBeanFromSpringContext(type);
        }
        return t;
    }

    private <T> T getBeanFromSpringContext(Class<T> type) {
        return this.applicationContext.getBean(type);
    }
}
